/**
 * Created by qunxing.du on 2016/7/28.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.gdyc.memento;

import com.hw.one.collect.memento.CareTaker;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 */
public class GdycCareTaker extends CareTaker<Integer,GdycMemento> {
    private static Map<Integer,GdycMemento> mementos = new ConcurrentHashMap<>();
    private final static int MAX_COUNT = 3;//拉取次数
    private GdycCareTaker(){}
    private static GdycCareTaker gdycCareTaker;
    public static GdycCareTaker newInstance() {
        if (gdycCareTaker == null){
            gdycCareTaker = new GdycCareTaker();
        }
        return gdycCareTaker;
    }
    /**
     * 添加备忘录
     *
     * @param key
     * @param memento
     */
    @Override
    public synchronized void add(Integer key, GdycMemento memento) {
        mementos.put(key,memento);
    }

    /**
     * 查询备忘录
     *
     * @param key
     * @return
     */
    @Override
    public synchronized GdycMemento get(Integer key) {
        return mementos.get(key);
    }

    /**
     * 获取所有Memento
     *
     * @return
     */
    @Override
    public synchronized Map<Integer, GdycMemento> getAll() {
        return mementos;
    }

    /**
     * 移除备忘录
     *
     * @param key
     */
    @Override
    public synchronized void remove(Integer key) {
        mementos.remove(key);
    }

    /**
     * 更新备忘录
     *
     * @param key
     * @param memento
     */
    @Override
    public synchronized void update(Integer key, GdycMemento memento) {
        int count = memento.getCount();
        //如果备忘次数超过设定次数则抛弃
        if(count >= MAX_COUNT){
            remove(key);
        }else {
            memento.setCount(++count);
            mementos.put(key,memento);
        }
    }

    /**
     * 保存或更新
     *
     * @param key
     * @param memento
     */
    @Override
    public synchronized void saveOrUpdate(Integer key, GdycMemento memento) {
        GdycMemento orginMemento = get(key);
        if(orginMemento != null){
            update(key,orginMemento);
        }else {
            add(key,memento);
        }
    }
}
